package general.helperclasses.logger;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

/**
 * Simple thread-safe logging class, which is able to print out all passed log-entries
 * 
 * @author tim
 * @version 0.5.0
 * @since 0.4.1
 */
public class Logger{

	private static Vector<LogEntry> entrys= new Vector<LogEntry>();
	private static int pos = 0;
	private static LoggingLevel level = LoggingLevel.NONE;
	
	public static void setDebugLevel(LoggingLevel level)
	{
		Logger.level = level;
	}
	
	/**
	 * @param classname Name of the class which passed this entry
	 * @param message The Messagetext
	 */
	public static void addEntry(LoggingLevel level, String message) {
		LogEntry e = new LogEntry(level, message);
		
		if(Logger.level.isHigher(level))
		{
			synchronized (entrys) {
				entrys.add(e);	
			}
		}
	}

	/**
	 * This method prints out all entries
	 */
	public static void printAll() {
		synchronized (entrys) {
			for(LogEntry e: entrys)
			{
				System.out.println(e);
			}
		}
	}

	/**
	 * This method prints out the last added log-entry, but does not change the log
	 */
	public static void printLast() 
	{
		synchronized (entrys) 
		{
			for(;pos < entrys.size(); pos++)
			{
				System.out.println(entrys.get(pos));
			}	
		}
	}

	public static void saveToFile()
	{
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
			FileWriter fw = new FileWriter("log_"+sdf.format(new Date())+".txt");
			synchronized (entrys) {
				for(LogEntry e: entrys)
				{
					fw.write(e.toString()+"\n");
				}
			}
			fw.flush();
			fw.close();
		}catch (IOException e) {
			// TODO: handle exception
		}
	}
}
